import axios from 'axios'
import {ElMessage} from 'element-plus'
import config from '@/config'

/**
 * 创建axios实例
 */
const request = axios.create({
    baseURL: config.api.baseURL,
    timeout: config.api.timeout,
    headers: {
        'Content-Type': 'application/json'
    }
})

/**
 * 请求拦截器
 */
request.interceptors.request.use(
    (requestConfig) => {
        // 添加token到请求头
        const token = localStorage.getItem(config.auth.tokenKey)
        if (token) {
            requestConfig.headers.Authorization = `Bearer ${token}`
        }

        if (config.dev.debug) {
            console.log('发送请求:', requestConfig.method?.toUpperCase(), requestConfig.url, requestConfig.data)
        }
        return requestConfig
    },
    (error) => {
        console.error('请求错误:', error)
        return Promise.reject(error)
    }
)

/**
 * 响应拦截器
 */
request.interceptors.response.use(
    (response) => {
        const {data} = response

        console.log('收到响应:', response.config.url, data)

        // 检查业务状态码
        if (data.code === 200) {
            return data
        } else {
            // 业务错误
            const message = data.message || '请求失败'
            ElMessage.error(message)
            return Promise.reject(new Error(message))
        }
    },
    (error) => {
        console.error('响应错误:', error)

        // 处理HTTP错误
        let message = '网络错误，请重试'

        if (error.response) {
            const {status, data} = error.response

            switch (status) {
                case 401:
                    message = '登录已过期，请重新登录'
                    // 清除token
                    localStorage.removeItem(config.auth.tokenKey)
                    // 跳转到登录页
                    window.location.href = config.auth.loginPath
                    break
                case 403:
                    message = '没有权限访问'
                    break
                case 404:
                    message = '请求的资源不存在'
                    break
                case 500:
                    message = '服务器内部错误'
                    break
                default:
                    message = data?.message || `请求失败 (${status})`
            }
        } else if (error.code === 'ECONNABORTED') {
            message = '请求超时，请重试'
        }

        ElMessage({
            type: 'error',
            message,
            duration: config.message.duration,
            showClose: config.message.showClose
        })
        return Promise.reject(error)
    }
)

export default request
